package com.mlz.mlzmall.ui.activity.act.personal;

import android.app.Activity;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.google.gson.Gson;
import com.mlz.mlzmall.R;
import com.mlz.mlzmall.bean.StatusBean;
import com.mlz.mlzmall.ui.activity.act.base.TopTitleView;
import com.mlz.mlzmall.ui.activity.act.main.MyApplication;
import com.mlz.mlzmall.ui.activity.act.personal.NetworkRequest.VolleyBaseActivity;
import com.mlz.mlzmall.ui.adapter.base.MallHolder;
import com.mlz.mlzmall.ui.adapter.base.ShopMallAdapter;
import com.mlz.mlzmall.ui.model.AddressAllTagBean;
import com.mlz.mlzmall.ui.model.AddressAllTagBean.ProvinceBean;
import com.mlz.mlzmall.ui.model.AddressAllTagBean.ProvinceBean.CityBean;
import com.mlz.mlzmall.ui.model.AddressAllTagBean.ProvinceBean.CityBean.AreaBean;
import com.mlz.mlzmall.ui.utils.mlz.ConfigInfo;
import com.mlz.mlzmall.ui.utils.mlz.URL;
import com.mlz.mlzmall.ui.utils.util.LogUtils;
import com.mlz.mlzmall.ui.utils.util.ScreenUtils;
import com.mlz.mlzmall.ui.utils.vali.PhoneValidate;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * Created by Administrator on 2016/5/18.
 */
public class AddNewAddress extends VolleyBaseActivity {

    private EditText tvReceiverName;//收货人
    private EditText tvDetailAddress;//详细收货地址
    private EditText tvPhoneNumber;//联系方式
    private CheckBox cbDefaultAddress;//是否设置默认地址

    private Button btnSaveAddress;//保存地址按钮

    private int addressId;
    private String userName;
    private String phoneNumber;
    private int regionCode;
    private String address;
    private String postcode;
    private boolean defaultAddress;
    private List<ProvinceBean> province;
    private List<CityBean> city=new ArrayList<CityBean>();
    private List<AreaBean> area=new ArrayList<AreaBean>();
    private static View pw;
    private static ListView listView;
    private static PopupWindow pWindow;

    // 被选中状态，把当前的地址设为默认地址
    boolean bSelected = false;
    private TextView tv_area;
    private TextView tv_city;
    private TextView tv_province;
    private StringBuilder builder;
    private AddressAllTagBean ab;
    private boolean isDefaultAddress;//是否为默认地址

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_new_address);//添加新地址
        setViewContent();
        initView();
    }
    private void setViewContent() {
        TopTitleView loginTopTitle = (TopTitleView) findViewById(R.id.login_top_title);
        loginTopTitle.setLeftButtonContent(null, R.mipmap.pic_2_1_btn_back, null);
        loginTopTitle.setTitleButtonContent("添加地址", null, null);
        loginTopTitle.setOnLeftButtonClickListener(new TopTitleView.OnLeftButtonClickListener() {
            @Override
            public void onLeftBtnClick(View button) {
                finish();
                AddNewAddress.this.overridePendingTransition(R.anim.right_in,R.anim.right_out);
            }
        });
    }
    private void initView() {
        tvReceiverName = (EditText) findViewById(R.id.tv_receiver_name);
        tvDetailAddress = (EditText) findViewById(R.id.tv_detail_address);
        tvPhoneNumber = (EditText) findViewById(R.id.tv_phone_number);
        cbDefaultAddress = (CheckBox) findViewById(R.id.cb_default_address);
        cbDefaultAddress.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    isDefaultAddress = isChecked;
            }
        });

        tv_province = (TextView) findViewById(R.id.tv_province);
        tv_city = (TextView) findViewById(R.id.tv_city);
        tv_area = (TextView) findViewById(R.id.tv_area);
        btnSaveAddress = (Button) findViewById(R.id.btn_save_address);
        tv_province.setOnClickListener(this);
        tv_city.setOnClickListener(this);
        tv_area.setOnClickListener(this);
        btnSaveAddress.setOnClickListener(this);
    }
    private void getPostCode(String str) {
        Gson gson=new Gson();
         ab = gson.fromJson(str, AddressAllTagBean.class);
        province=ab.getProvince();
    }

    private String ReadStringJson() {
        try {
            InputStreamReader isr = new InputStreamReader(AddNewAddress.this.getAssets().open("postcode.json"), "UTF-8");
            BufferedReader br = new BufferedReader(isr);
            String line;
            builder = new StringBuilder();//读取数据到StringBuilder中
            while ((line = br.readLine()) != null) {
                builder.append(line);
            }
            br.close();
            isr.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return builder.toString();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_province:
                getPostCode(ReadStringJson());
                setAddress(1,tv_province);
                tv_city.setText("");
                tv_area.setText("");
                break;
            case R.id.tv_city:
                setAddress(2,tv_city);
                tv_area.setText("");
                break;
            case R.id.tv_area:
                setAddress(3,tv_area);
                break;
            case R.id.btn_save_address://保存地址的监听
                //保存地址,将点击的条目地址保存（界面添加该地址条目，数据库要更新）
                userName = tvReceiverName.getText().toString();
                address = tvDetailAddress.getText().toString();
                phoneNumber = tvPhoneNumber.getText().toString();
                if (userName.length() == 0) {
                    showToast("请填写收货人");
                } else if (address.length() == 0) {
                    showToast("请填写详细地址");
                } else if (phoneNumber.length()==0) {
                    showToast("请填写联系方式");
                }else if(!PhoneValidate.isPhone(phoneNumber)){
                    showToast("手机号码格式不正确");
                } else {
                    postCreateAddress(userName, phoneNumber, address, postcode,defaultAddress);
                }
                break;
        }
    }


    public void setAddress(final int iii,final TextView tv) {
        //  退出对话框
        pw = LayoutInflater.from(AddNewAddress.this).inflate(R.layout.dialog_list, null);
        listView = (ListView) pw.findViewById(R.id.listView);
        if (iii == 1) {
            ProvinceAdapter adapter = new ProvinceAdapter(this, province, R.layout.spinner_display_style);
            listView.setAdapter(adapter);
        }
        if (iii == 2) {
            CityAdapter adapter = new CityAdapter(this, city, R.layout.spinner_display_style);
            listView.setAdapter(adapter);
        }
        if (iii == 3) {
            AreaAdapter adapter = new AreaAdapter(this, area, R.layout.spinner_display_style);
            listView.setAdapter(adapter);
        }
        pWindow = new PopupWindow(pw, tv.getWidth(),ScreenUtils.getScreenWidth(this)*2/3);//弹框显示大小
        pWindow.setFocusable(true);
        pWindow.setBackgroundDrawable(new ColorDrawable(0x55000000));//设置背景为透明
       // pWindow.setAnimationStyle(R.style.AnimationPush);
        //   pWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
        pWindow.showAsDropDown(tv);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (iii == 1) {
                    tv.setText(province.get(position).getName());
                    if(province!=null||!province.isEmpty()) {
                        city = province.get(position).getCity();
                    }
                }
                if (iii == 2) {
                    tv.setText(city.get(position).getName());
                    if(city!=null||!city.isEmpty()) {
                        area = city.get(position).getArea();
                    }
                }
                if (iii == 3) {
                    tv.setText(area.get(position).getName());
                    regionCode=Integer.parseInt(area.get(position).getCode());
                    if(area!=null||!area.isEmpty()) {
                    }
                }
                pWindow.dismiss();
            }
        });
    }

    private class ProvinceAdapter extends ShopMallAdapter <ProvinceBean> {
        public ProvinceAdapter(Activity activity, List<ProvinceBean> list, int id_layout) {
            super(activity,list,id_layout);
        }

        @Override
        public void convert(MallHolder holder, ProvinceBean o) {
            holder.setText(R.id.tv_spinner,o.getName());
        }
    }

    private class CityAdapter extends ShopMallAdapter<CityBean> {
        public CityAdapter(Activity activity, List<CityBean> list, int id_layout) {
            super(activity,list,id_layout);
        }

        @Override
        public void convert(MallHolder holder, CityBean o) {
            holder.setText(R.id.tv_spinner,o.getName());
        }
    }

    private class AreaAdapter extends ShopMallAdapter<AreaBean>  {
        public AreaAdapter(Activity activity, List<AreaBean> list, int id_layout) {
            super(activity,list,id_layout);
        }

        @Override
        public void convert(MallHolder holder, AreaBean o) {
            holder.setText(R.id.tv_spinner,o.getName());
        }
    }

    //新建收货地址
    private void postCreateAddress(String userName, String phoneNumber, String address, String postcode,Boolean defaultAddress) {
        tag = "rPost";
        Map<String, String> param1 = new HashMap<String, String>();
        param1.put("fullname", isNull(userName));
        param1.put("shippingTelephone", isNull(phoneNumber));
        param1.put("regionCode", isNull(regionCode + ""));
        param1.put("address", isNull(address));
        param1.put("postcode", "");
        param1.put("defaultAddress", isDefaultAddress+ "");

        JSONObject jsonObject = new JSONObject(param1);
        LogUtils.d("添加的地址信息："+jsonObject.toString());
        JsonRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, URL.ADDRESS.ADD, jsonObject, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                LogUtils.d(jsonObject.toString());
                Gson gson = new Gson();
                StatusBean sb = gson.fromJson(jsonObject.toString(), StatusBean.class);
                if (sb.getStatus() == 0) {
                    showToast(sb.getMsg());
                    finish();
                    AddNewAddress.this.overridePendingTransition(R.anim.right_in, R.anim.right_out);
                }else {
                    showToast("保存失败");
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.e(tag, volleyError.getMessage(), volleyError);
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put(ConfigInfo.CHARSET, ConfigInfo.UTF8);
                map.put(ConfigInfo.COOKIE, ConfigInfo.COOKIE_KEY + sessionId);
                map.put(ConfigInfo.TYPE, ConfigInfo.TYPE_KEY);
                return map;
            }
        };
        //设置该请求的标签
        jsonRequest.setTag(tag);
        //将该请求添加到请求队列
        ((MyApplication) getApplication()).getRequestQueue().add(jsonRequest);
    }

}
